import React,{Component} from 'react';
import {View,Text,Image,TouchableOpacity,ScrollView} from 'react-native';
import CLNavigatorHeader from '../../component/CLNavigatorHeader';
import {connect} from 'react-redux';
import {naviPush,naviBack} from '../../navigatorApp/actions';
import { showLoading , hideLoading , getConfig , getLocation , setBlueTooth ,printer, toast  ,  choosePhoto, setConfigValue , microPhotoListener} from '../../utils/NativeUtil';
import hdstyles from './styles'
import Styles from '../cpgl/styles'
import BigButton from '../../component/BigButton'
import themeconfig from '../../config/theme'
import {GetWeiZhangTCInfo,WeiZhangTC_Update} from './actions'
import {setPrinter , GetWeiZhangTCNum} from '../main/actions';
import config from '../../config/config';
const md5 = require('md5');
const imageOptions = ['取消', '拍照上传'];
const CANCEL_INDEX = 0;
import ChoosePhotoView from '../compents/ChoosePhotoView';
import ActionSheet from 'react-native-actionsheet';
import { Cpgl_Printer_New , getWtContent} from './actions';
import {stringToUtf8ByteArray , utf8ByteArrayToString} from '../../utils/StringUtil';
import moment  from 'moment';


let TelPhone ="";
let CLAddress = "";

class HistoryDetail2 extends Component {
    static navigationOptions = ({ navigation, screenProps }) => ({
        header: <CLNavigatorHeader navigation={navigation} title="未上传记录详情"/>
    });
    constructor(props){
        super(props);
        this.state={
            datainfo:{},
            photos:[]
        }
        this.photoLstTag = ''
        this.printTel = ''
        this.printAdd = ''
        this.WtContent = {};
    }


    componentDidMount(){
        let params={
            UserGuid : this.props.userGuid,
            keyWords: md5(this.props.userGuid + config.md5Secret),
            RowGuid : this.props.navigation.state.params.rowguid
        }
        GetWeiZhangTCInfo(params).then(res=>{
            console.log(res)
            let info = res[0];
            let tempphoto = []
            if (info.filePaths != null){
                let urls = info.filePaths.split(',')
                urls.map((item , index) => {
                    if (item.length != ''){
                        tempphoto.push({url: 'http://221.224.118.58:5080/SZCG/QingWuMana/'  + item , id: index  , title: ''});
                    }
                })
            }
            this.setState({
                datainfo: info,
                photos: tempphoto
            })
        }).catch(msg=>{
            console.log(msg)
        })


        getWtContent(this.props.userGuid).then(res => {
            if (res.length>0) {
                this.WtContent = res[0]
            }
        }).catch(msg => {

        });
    }

    submit=()=>{
        let params2={
            RowGuid: this.props.navigation.state.params.rowguid,
            UserGuid: this.props.userGuid,
            Password : md5(this.props.userGuid + config.md5Secret)
        }

        if (this.state.photos.length < 3) {
            toast('请至少上传三张照片')
            return ;
        }

        WeiZhangTC_Update(params2).then(res=>{
            console.log(res)
            let params={
                UserGuid : this.props.userGuid,
                KeyWords : md5(this.props.userGuid + config.md5Secret)
            }
            this.props.GetWeiZhangTCNum(params);
            if (this.props.navigation.state.params.reload != undefined){
                this.props.navigation.state.params.reload();
            }
            this.props.navigation.goBack();

        }).catch(msg=>{
            console.log(msg)
        })
    }


    chooseItemClick = (item, tag) => {
        this.photoLstTag = tag;
        this.phtotoItem = item;
        this.ImageActionSheet.show();
    };

    handleImagePress = (i) => {
        let type = "choose";
        let size_w = 0;
        let size_h = 0;
        if (i == 1) {
            type = "takephoto"
        } else if (i == 2) {
            type = "choose"
        } else {
            return;
        }
        
        

        let params = {
            type : type,
            fileType: this.photoLstTag,
            recordGuid: this.props.navigation.state.params.rowguid,
            photos: this.state.photos
        }
        choosePhoto(params , data => {
             let imgs = data.imgs;
             console.log(imgs)
             if (imgs != ''){
                if (this.photoLstTag == 'cpgl'){
                    let imgItem = imgs.split(';');
                    let lst = [];
                    imgItem.map(item => {
                        if (item.length != ''){
                            lst.push({url: item , id: lst.length  , title: ''});
                        }
                    })
                    this.setState({photos: lst});
                } else {
                    let first  = imgs.substring(0,1);
                    console.log(first);
                    this.setState({car_cp:first});
                    let cityno = imgs.substring(1,2);
                    this.setState({car_city_cp:cityno})
                    let end = imgs.substring(2);
                    console.log(end);
                    this.setState({car_no:end});
                }
             }
        });
    };

    delPhotos = (item , index) => {
        let photos = this.state.photos;
        ArrayUtil.delete(photos , item);
        this.setState({photos:photos})
    }

    printerAction = () => {
        

         // 判断蓝牙连接状态
         if (this.props.blueToothState == '未连接') {
            toast ('请先连接打印机')
            return;
        }

        let params  = {
            RowGuid: this.props.navigation.state.params.rowguid,
            Password : md5(this.props.navigation.state.params.rowguid + config.md5Secret)
        }

        console.log(params);
        Cpgl_Printer_New(params).then(res => {
            this.toPrintAction(); 
            this.updateRecordNum();
        }).catch(msg => {
            toast(msg);
        });
    }

    updateRecordNum  = () => {
        let params={
            UserGuid : this.props.userGuid,
            KeyWords : md5(this.props.userGuid + config.md5Secret)
        }
        this.props.GetWeiZhangTCNum(params);
    }


    toPrintAction = () => {

        // 判断蓝牙连接状态
        if (this.props.blueToothState == '未连接') {
            toast ('请先连接打印机')
            return;
        }

        console.log('toPrintAction')

        // this.setCLAddres();
        
        let carNo_b = stringToUtf8ByteArray(this.state.datainfo.CP);
        let carNo = utf8ByteArrayToString(carNo_b);

        let TDBH_b = stringToUtf8ByteArray(this.state.datainfo.TDBH);
        let TDBH = utf8ByteArrayToString(TDBH_b);

        let date_b = stringToUtf8ByteArray(moment().format("YYYY年MM月DD日HH时mm分"));
        let date = utf8ByteArrayToString(date_b);

        let detailAddress_b = stringToUtf8ByteArray(this.state.datainfo.WZDD);
        let detailAddress = utf8ByteArrayToString(detailAddress_b);

        let Tel_b = stringToUtf8ByteArray(this.printTel);
        let Tel = utf8ByteArrayToString(Tel_b);

        let cl_b = stringToUtf8ByteArray(this.printAdd);
        let cl = utf8ByteArrayToString(cl_b);

        let printParams = {
            carNo: carNo ,
            TDBH: TDBH ,
            TDDate: date,
            TDAddress : detailAddress,
            CLPhone: this.WtContent.LXDH || '',
            CLAddress : cl,
            rowGuid: this.RowGuid,
            BGDW: this.WtContent.BGDW || '',
            CLDD: this.WtContent.CLDD || '',
            JZDW: this.WtContent.JZDW || ''
        };


        console.log('printParams' , printParams)

        printer(printParams,res => {
            this.setState({printed:true})
            toast('打印成功')
        });
    }

    setBlueTooth = () => {
        setBlueTooth(res => {
            if (res.name && res.name.length > 0 ){
                this.props.setPrinter(res.name)
            }
        });
    }

    setCLAddres(){
        let DeptCode = this.props.depCode;
        let  TelPhone = ''
        let CLAddress = ''
        if(DeptCode == "032001")
		{
			TelPhone="0512-58305786";
			CLAddress="张家港市城市管理行政执法局处理窗口（白鹿路99号）";
		}
		if(DeptCode ==  "032002")
		{
			TelPhone="0512-58697718、0512-58305791";
			CLAddress="张家港市城市管理行政执法局处理窗口（白鹿路99号）";
		}
		if(DeptCode == "032003")
		{
			TelPhone="0512-55395819";
			CLAddress="张家港市城市管理行政执法局处理窗口（白鹿路99号）";
		}
		if(DeptCode == "032004")
		{
			TelPhone="0512-58305793、0512-58671595";
			CLAddress="张家港市城市管理行政执法局处理窗口（白鹿路99号）";
		}
		if(DeptCode ==  "032005")
		{
			TelPhone="0512-58305783";
			CLAddress="张家港市城市管理行政执法局处理窗口（白鹿路99号）";
		}
		if(DeptCode ==  "032006")
		{
			TelPhone="0512-58690778";
			CLAddress="张家港市城市管理行政执法局处理窗口（白鹿路99号）";
		}
		if(DeptCode ==  "033001")
		{
			TelPhone="0512-58117802、0512-58117222";
			CLAddress="张家港市金港镇中圩西路13号";
		}
		if(DeptCode  ==  "033002")
		{
			TelPhone="0512-56991781、0512-56991782";
			CLAddress="张家港市杨舍镇塘市镇中路工商所东侧弄堂、塘市西菜场西侧";
		}
		if(DeptCode  ==  "033003")
		{
			TelPhone="0512-58106080";
			CLAddress="张家港市塘桥镇202县道（老204国道）800号";
		}
		if(DeptCode ==  "033004")
		{
			TelPhone="0512-58950119";
			CLAddress="张家港市锦丰镇锦花路72号";
		}
		if(DeptCode ==  "033005")
		{
			TelPhone="0512-58422115";
			CLAddress="张家港市凤凰镇张市路66号";
		}
		if(DeptCode ==  "033006")
		{
			TelPhone="0512-58960161";
			CLAddress="张家港市乐余镇人民路张家港市农村商业银行西侧向北50米";
		}
		if(DeptCode ==  "033007")
		{
			TelPhone="0512-58907229、18013610165";
			CLAddress="张家港市南丰镇社会管理服务中心";
		}
		if(DeptCode ==  "033008")
		{
			TelPhone="0512-56936225";
			CLAddress="张家港市大新镇星光路";
		}
		if(DeptCode ==  "033009")
		{
			TelPhone="0512-58645891";
			CLAddress="张家港市现代农业示范园区红旗路";
        }
        this.printAdd = CLAddress;
        this.printTel = TelPhone;
    }


    render(){
        return(
            <ScrollView style={hdstyles.totalbox}>
                <View style={hdstyles.titbox}>
                <Image source={require('../../image/ico_time.png')} style={hdstyles.titImg} />
                   <Text style={hdstyles.tit}>{this.state.datainfo.JCSJ} 上传</Text>
                </View>
                <View style={hdstyles.list}>
                    <View style={[Styles.itemView,{minHeight:35}]}>
                        <Text style={hdstyles.leftfont}>贴单编码</Text>
                        <Text style={hdstyles.rightfont}>{this.state.datainfo.TDBH}</Text>
                    </View>
                </View>
                <View style={hdstyles.list}>
                    <View style={[Styles.itemView,{minHeight:35}]}>
                        <Text style={hdstyles.leftfont}>号牌种类</Text>
                        <Text style={hdstyles.rightfont}>{this.state.datainfo.HPZL}</Text>
                    </View>
                </View>
                <View style={hdstyles.list}>
                    <View style={[Styles.itemView,{minHeight:35}]}>
                        <Text style={hdstyles.leftfont}>车牌号&emsp;</Text>
                        <Text style={hdstyles.rightfont}>{this.state.datainfo.CP}</Text>
                    </View>
                </View>
                <View style={hdstyles.list}>
                    <View style={[Styles.itemView,{minHeight:35}]}>
                        <Text style={hdstyles.leftfont}>违停方向</Text>
                        <Text style={hdstyles.rightfont}>{this.state.datainfo.WTFX}</Text>
                    </View>
                </View>
                <View style={hdstyles.list}>
                    <View style={[Styles.itemView,{minHeight:35}]}>
                        <Text style={hdstyles.leftfont}>违章地点</Text>
                        {/* <View style={hdstyles.place}>
                        <Text style={hdstyles.rightfont}>张家港市</Text>
                        <View style={hdstyles.blank1} /> */}
                        <Text style={hdstyles.rightfont}>{this.state.datainfo.WZDD}</Text>
                        {/* </View> */}
                    </View>
                </View>
                <View style={hdstyles.list}>
                    <View style={[Styles.itemView,{minHeight:35}]}>
                        <Text style={hdstyles.leftfont}>配对队员</Text>
                        <Text style={hdstyles.rightfont}>{this.state.datainfo.PDRY}</Text>
                    </View>
                </View>
                <View style={hdstyles.list}>
                
                <ChoosePhotoView 
            onItemClick={(item) => this.chooseItemClick(item, 'cpgl')}
            delAction={(item , index)=>this.delPhotos(item, index)}
            images={this.state.photos} 
            num={3}
            maxNum={3}
            itemheight={80}/>
            </View>
            

            <View style={{flexDirection:'row' , paddingHorizontal:15 , alignItems:'center'}}>
                <Text style={Styles.lableText}>蓝牙</Text>
                <Text style={[Styles.rightValue,{flex:1}]}>{this.props.blueToothState}</Text>
                <TouchableOpacity style={Styles.rightBtn} onPress={this.setBlueTooth}>
                    <Text style={Styles.settingTxt}>设置</Text>
                </TouchableOpacity>
            </View>

            
            <ActionSheet
                ref={o => this.ImageActionSheet = o}
                title="选择图片"
                options={imageOptions}
                cancelButtonIndex={CANCEL_INDEX}
                onPress={this.handleImagePress}/>
                
                <BigButton label='打印' backgroundColor={themeconfig.blue1Color} style={{marginTop:20}}  onPress={this.printerAction}/>
       
                <BigButton label='提交' backgroundColor={themeconfig.blue1Color} style={{marginTop:20}} onPress={this.submit}/>
            </ScrollView>
        )
    }
}

const mapStateToProps = state => ({
    userGuid: state.main.UserGuid,
    blueToothState: state.main.printerName,
    depCode: state.main.DeptCode
});

const mapDispatchToProps = dispatch => ({
    naviPush: (routeName, params) => {
        dispatch(naviPush(routeName, params));
    },
    naviBack : (routeName) => {
        dispatch(naviBack(routeName));
    },
    GetWeiZhangTCNum: (params) => {
        dispatch(GetWeiZhangTCNum(params))
    },
    setPrinter: (name) => {
        dispatch(setPrinter(name));
    },
});


export default connect(
    mapStateToProps,
    mapDispatchToProps
)(HistoryDetail2);